package com.xiaobai.frame.config.dict;

import cn.hutool.core.util.StrUtil;
import com.xiaobai.frame.service.IDictService;
import com.xiaobai.frame.utils.RedisTool;
import com.xiaobai.model.entity.system.Dict;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xiaobai.frame.config.redis.RedisKey.DICT_DATA;


@Component
@RequiredArgsConstructor
@Slf4j
//在启动之后自动运行一次
public class LocationConfig implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(LocationConfig.class);
    private final IDictService iDictService;
    private final RedisTool redisTool;


    @Override
    public void run(String... args) {
        redisTool.deleteObject(DICT_DATA);
        List<Dict> dictList = iDictService.queryList(null);
        Map<String, Map<String, String>> map = dictList.stream()
            .filter(dict -> StrUtil.isNotBlank(dict.getDictKey()))
            .collect(Collectors.groupingBy(Dict::getCode,
                Collectors.toMap(
                    Dict::getDictKey, Dict::getDictValue,
                    (existing, replacement) -> existing)
            ));
        logger.info("字典数据初始化成功");
        redisTool.setCacheMap(DICT_DATA, map);
    }


}
